import streamlit as st
import requests
from PIL import Image

st.title("图片上传 Demo (FastAPI + Streamlit)")

uploaded_file = st.file_uploader("请选择一张图片", type=["jpg", "jpeg", "png"])

if uploaded_file is not None:
    # 预览本地上传的图片
    image = Image.open(uploaded_file)
    st.image(image, caption="待上传的图片", use_column_width=True)

    if st.button("上传到服务器"):
        files = {"file": (uploaded_file.name, uploaded_file.getvalue(), uploaded_file.type)}
        response = requests.post("http://127.0.0.1:8000/upload/", files=files)

        if response.status_code == 200:
            res_json = response.json()
            st.success(f"上传成功！文件名: {res_json['filename']}")
            st.markdown(f"图片链接: [点击查看]({res_json['url']})")
            st.image(res_json['url'], caption="服务器上的图片", use_column_width=True)
        else:
            st.error("上传失败！")
